package com.white.loglib;

import android.content.Context;
import android.util.Log;


public class L
{
    private static final int MAX_LOG_LENGTH = 2000;
    public static LogPrintStrategy logStrategy;
    private static boolean isDebug = BuildConfig.DEBUG;
    private static String TAG = "s";

    public static void initStrategy(Context context, Object extra)
    {
        if (logStrategy != null)
        {
            logStrategy.init(context, extra);
        }
    }

    public static void i(String msg)
    {
        print(msg, 0);
    }

    public static void d(String msg)
    {
        print(msg, 1);
    }

    public static void e(String msg)
    {
        print(msg, 2);
    }

    private static void print(String msg, int type)
    {
        if(isDebug)
        {
            printLogcat(msg, type);
        }
        if(logStrategy != null)
        {
            printUseStrategy(type, msg);
        }
    }

    private static void printLogcat(String msg, int type)
    {
        long length = msg.length();
        if (length > MAX_LOG_LENGTH)
        {
            int size = (int) (length / MAX_LOG_LENGTH);
            int mode = (int) (length % MAX_LOG_LENGTH);
            int start = 0;
            int end = 0;
            for (int i = 0; i < size; i++)
            {
                end = (i + 1) * MAX_LOG_LENGTH;
                String cs = msg.substring(start, end);
                start = end;
                logType(type, cs);
            }
            if (mode != 0)
            {
                String endString = msg.substring(size * MAX_LOG_LENGTH);
                logType(type, endString);
            }
        } else
        {
            logType(type, msg);
        }
    }

    /**
     * 0 => info
     * 1 => debug
     * 2 => error
     * @param t
     * @param msg
     */
    private static void logType(int t, String msg)
    {
        switch (t)
        {
            case 0:
                Log.i(TAG, msg);
                break;
            case 1:
                Log.d(TAG, msg);
                break;
            case 2:
                Log.e(TAG, msg);
                break;
        }
    }

    private static void printUseStrategy(int type, String msg)
    {
        logStrategy.print(type, msg);
    }

    public static void release()
    {
        if (logStrategy != null)
        {
            logStrategy.destroy();
            logStrategy = null;
        }
    }
}
